#include "BlockQueue.hpp"
#include <pthread.h>
#include <ctime>
#include <unistd.h>
#include "Task.hpp"


using std::cout;
using std::endl;


void *consumer(void *args)
{
    // BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        // 消费活动
        sleep(1);
        // 1.获取数据
        // int data = 0;


        Task t;
        bq->pop(&t);
        // 2.处理数据
        // cout << "consumer pop data:" << data << endl;
        t();
        cout << pthread_self() << " | consumer: " << t.formatArg() << t.formatRes() << endl;
    }
}


void *productor(void *args)
{
    // BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);


    while (true)
    {
        // 生产活动
        //sleep(1);
        // 1.生产数据
        // int data = rand() % 10 + 1;


        int x = rand() % 20 + 1;
        int y = rand() % 10 + 1;
        char op = ops[rand() % ops.size()];
        Task t(x, y, op);
        // 2.推送数据到缓冲区
        // cout << "productor push data:" << data << endl;
        bq->push(t);
        cout << pthread_self() << " | productor: " << t.formatArg() << '?' << endl;
    }
}


int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());
    // BlockQueue<int> *bq = new BlockQueue<int>();
    BlockQueue<Task> *bq = new BlockQueue<Task>();


    pthread_t c[2], p[3];


    pthread_create(&c[0], nullptr, consumer, bq);
    pthread_create(&c[1], nullptr, consumer, bq);
    pthread_create(&p[0], nullptr, productor, bq);
    pthread_create(&p[1], nullptr, productor, bq);
    pthread_create(&p[2], nullptr, productor, bq);


    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(p[2], nullptr);


    delete bq;
    return 0;
}